package list_performance;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * ArrayList和LinkList性能
 */
public class Main {

    public static void main(String[] args) {
        addArray();
        addLink();


    }

    //添加Link
    public static LinkedList<Integer> addLink(){
        long oldTime = System.currentTimeMillis();
        LinkedList<Integer> list = new LinkedList<>();
        for (int i = 0; i < 800000; i++) {
            list.add(i);
        }
        System.out.println("添加Link耗时 " +(System.currentTimeMillis()-oldTime));
        foreachTime(list,list.getClass().getName());
        forTime(list,list.getClass().getName());

        return list;
    }
    //添加Array
    public static ArrayList<Integer> addArray(){
        long oldTime = System.currentTimeMillis();
        ArrayList<Integer> list = new ArrayList<>(800000);
        for (int i = 0; i < 800000; i++) {
            list.add(i);
        }
        System.out.println("添加Array耗时 " +(System.currentTimeMillis()-oldTime));
        foreachTime(list,list.getClass().getName());
        forTime(list,list.getClass().getName());
        return list;
    }

    private static void foreachTime(List<Integer> list,String ListName){
        long oldTime = System.currentTimeMillis();
        int sum = 0;
        for (int count :
                list) {
            sum += count;
        }
        System.out.println(ListName+" foreach遍历 耗时" +(System.currentTimeMillis()-oldTime));
    }

    private static void forTime(List<Integer> list,String ListName){
        long oldTime = System.currentTimeMillis();
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum*=list.get(i);
        }
        System.out.println(ListName+" for遍历 耗时" +(System.currentTimeMillis()-oldTime));
    }


}
